# 自动巡检处理类
import json
from typing import Dict, Any

import requests

# 部署服务器地址
DEPLOYMENT_API_URL = "http://127.0.0.1:8991/gen/doxc/bot"

supported_city_map = {
    "云平台": "YunPingTai",
    "锐通测试": "RuiTongTest",
    "广安": "GuangAn",
    "武胜": "WuSheng",
    "德阳": "DeYang",
    "荆州": "JingZhou",
    "雅安": "YaAn",
    "遂宁": "SuiNing",
    "黄陂": "HuangPi",
    "锐视机电": "RuiShiJiDian",
    "平凉": "PingLiang",
}


# invoke 方法
def invoke(message: str, tool: Dict[str, Any], result_params: Dict[str, Any]) -> str:
    print(f"成功调用工具: {tool['name']}")
    print("message", message)

    # 从 json 对象 result_params 中提取 extracted_info 即请求的参数
    params = {}
    if 'extracted_info' in result_params:
        params = result_params['extracted_info']

    # 检查必要参数
    required_params = tool.get('parameters', [])
    missing_params = [param for param in required_params if param not in params]

    if missing_params:
        return f"参数缺失: {', '.join(missing_params)}, 无法执行自动部署"

    # 确定 city 是否在 supported_city_map 中，存在替换成 value
    cityList = []
    if 'city' in params:
        citys = params['city']
        if isinstance(citys, str):
            # 将字符串按逗号分割并处理每个城市
            city_names = [city.strip() for city in citys.split(',')]
            for city in city_names:
                if city in supported_city_map:
                    cityList.append(supported_city_map[city])
                else:
                    cityList.append(city)  # 如果不在映射表中，保留原名
            params['city'] = cityList
        elif isinstance(citys, list):
            # 如果已经是列表，处理每个城市
            for city in citys:
                if city in supported_city_map:
                    cityList.append(supported_city_map[city])
                else:
                    cityList.append(city)
            params['city'] = cityList
    else:
        return "参数缺失: city, 无法执行自动部署"

    try:
        # 调用post请求
        response = requests.post(
            DEPLOYMENT_API_URL,
            json=params,
            headers={"Content-Type": "application/json"},
            timeout=30
        )

        # 检查响应
        if response.status_code == 200:
            # 返回调用信息
            required_str = str(tool.get('required'))
            return f"调用工具 {tool['name']}; 参数：{json.dumps(params, ensure_ascii=False)}。  {required_str}"
        else:
            return f"调用失败: {response.status_code}, {response.text}"

    except Exception as e:
        return json.dumps({
            "status": "error",
            "message": f"部署过程发生错误: {str(e)}",
            "details": None
        }, ensure_ascii=False)

    finally:
        # 处理完成后，清理资源或执行其他操作
        pass
